using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Services;

namespace WinformDevFramework
{
    public partial class Frmw_SaleReturnInWarehouse : BaseForm1
    {
        private Iw_SaleReturnInWarehouseServices _w_SaleReturnInWarehouseServices;
        private Iw_SaleReturnInWarehouseDetailServices _wSaleReturnInWarehouseDetailServices;
        private Iw_SaleReturnServices _wSaleReturnServices;
        private Iw_SaleReturnDetailServices _wSaleReturnDetailServices;
        private Iw_Warehouseervices _wWarehouseService;
        private ISysUserServices _wSysUserServices;
        public Frmw_SaleReturnInWarehouse(Iw_SaleReturnInWarehouseServices w_SaleReturnInWarehouseServices, Iw_SaleReturnInWarehouseDetailServices wSaleReturnInWarehouseDetailServices, Iw_SaleReturnServices wSaleReturnServices, Iw_SaleReturnDetailServices wSaleReturnDetailServices, Iw_Warehouseervices wWarehouseService, ISysUserServices sysUserServices)
        {
            _w_SaleReturnInWarehouseServices = w_SaleReturnInWarehouseServices;
            InitializeComponent();
            _wSaleReturnInWarehouseDetailServices = wSaleReturnInWarehouseDetailServices;
            _wSaleReturnServices = wSaleReturnServices;
            _wSaleReturnDetailServices = wSaleReturnDetailServices;
            _wWarehouseService = wWarehouseService;
            _wSysUserServices = sysUserServices;
        }

        public override void Init()
        {
            base.Init();
            //查询数据
            this.dataGridViewList.DataSource = GetData();

            // 设置隐藏列
            this.dataGridViewList.Columns["SaleReturnCode"].HeaderText = "销售退货单号";
            this.dataGridViewList.Columns["SaleCode"].HeaderText = "销售单号";
            this.dataGridViewList.Columns["CustomerCode"].HeaderText = "客户编码";
            this.dataGridViewList.Columns["CustomerName"].HeaderText = "客户名称";
            this.dataGridViewList.Columns["SaleReturnInWarehouseCode"].HeaderText = "入库单号";
            this.dataGridViewList.Columns["InvicesDate"].HeaderText = "单据日期";
            this.dataGridViewList.Columns["InvicesFile"].Visible = false;
            this.dataGridViewList.Columns["MakeUserID"].Visible = false;
            this.dataGridViewList.Columns["ReviewUserID"].Visible = false;
            this.dataGridViewList.Columns["Status"].Visible = false;
            this.dataGridViewList.Columns["Remark"].HeaderText = "备注";

            //设置明细 仓库
            WarehouseName.DataSource = _wWarehouseService.Query();
            WarehouseName.DisplayMember = "WarehouseName";
            WarehouseName.ValueMember = "WarehouseCode";

            MakeUser.DataSource = _wSysUserServices.Query();//值查找销售部门
            MakeUser.ValueMember = "ID";
            MakeUser.DisplayMember = "Fullname";
            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as w_SaleReturnInWarehouse;

            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.SaleReturnCode.Text = model.SaleReturnCode.ToString();
            this.SaleCode.Text = model.SaleCode.ToString();
            this.CustomerCode.Text = model.CustomerCode.ToString();
            this.CustomerName.Text = model.CustomerName.ToString();
            this.SaleReturnInWarehouseCode.Text = model.SaleReturnInWarehouseCode.ToString();
            this.InvicesDate.Text = model.InvicesDate.ToString();
            this.InvicesFile.Text = model.InvicesFile.ToString();
            this.MakeUser.SelectedValue = model.MakeUserID;
            this.ReviewUserID.Text = model.ReviewUserID.ToString();
            this.Status.Text = model.Status.ToString();
            this.Remark.Text = model.Remark.ToString();
            SetDataToDetail(GetDetailData(model.SaleReturnInWarehouseCode));
            SetToolButtonStatus(formStatus);
        }

        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            dataGridViewDetail.Rows.Clear();
            SetDataGridViewReadonlyStatus();
            MakeUser.SelectedValue = AppInfo.User.ID;
        }

        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            SetDataGridViewReadonlyStatus();
        }

        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    w_SaleReturnInWarehouse model = new w_SaleReturnInWarehouse();
                    // TODO获取界面的数据
                    model.SaleReturnCode = this.SaleReturnCode.Text;
                    model.SaleCode = this.SaleCode.Text;
                    model.CustomerCode = this.CustomerCode.Text;
                    model.CustomerName = this.CustomerName.Text;
                    if (string.IsNullOrEmpty(this.SaleReturnInWarehouseCode.Text))
                    {
                        model.SaleReturnInWarehouseCode = $"XSTHRK{DateTime.Now.ToString("yyyyMMddHHmmss")}";
                    }
                    else
                    {
                        model.SaleReturnInWarehouseCode = this.SaleReturnInWarehouseCode.Text;
                    }
                    model.InvicesDate = this.InvicesDate.Value;
                    model.InvicesFile = this.InvicesFile.Text;
                    model.MakeUserID = this.MakeUser.SelectedValue.ToInt32();
                    model.ReviewUserID = this.ReviewUserID.Text.ToInt32();
                    model.Status = this.Status.Text;
                    model.Remark = this.Remark.Text;

                    List<w_SaleReturnInWarehouseDetail> dataDetails = new List<w_SaleReturnInWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_SaleReturnInWarehouseDetail detail = new w_SaleReturnInWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["WarehouseName"].Value.ToString();
                            detail.WarehouseName = row.Cells["WarehouseName"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.SaleReturnDetailCode = row.Cells["SaleReturnDetailCode"].FormattedValue.ToString();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }

                    int id = _w_SaleReturnInWarehouseServices.AddSaleReturnInWarehouseInfo(model, dataDetails);
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                        txtID.Text = id.ToString();
                        SaleReturnInWarehouseCode.Text = model.SaleReturnInWarehouseCode;
                        SetDataToDetail(GetDetailData(model.SaleReturnInWarehouseCode));
                    }
                }
                // 修改
                else
                {
                    w_SaleReturnInWarehouse model = _w_SaleReturnInWarehouseServices.QueryById(int.Parse(txtID.Text));
                    // TODO获取界面的数据
                    model.SaleReturnCode = this.SaleReturnCode.Text;
                    model.SaleCode = this.SaleCode.Text;
                    model.CustomerCode = this.CustomerCode.Text;
                    model.CustomerName = this.CustomerName.Text;
                    model.SaleReturnInWarehouseCode = this.SaleReturnInWarehouseCode.Text;
                    model.InvicesDate = this.InvicesDate.Value;
                    model.InvicesFile = this.InvicesFile.Text;
                    model.MakeUserID = this.MakeUser.SelectedValue.ToInt32();
                    model.ReviewUserID = this.ReviewUserID.Text.ToInt32();
                    model.Status = this.Status.Text;
                    model.Remark = this.Remark.Text;

                    List<w_SaleReturnInWarehouseDetail> dataDetails = new List<w_SaleReturnInWarehouseDetail>();
                    foreach (DataGridViewRow row in dataGridViewDetail.Rows)
                    {
                        if (!row.IsNewRow)
                        {
                            w_SaleReturnInWarehouseDetail detail = new w_SaleReturnInWarehouseDetail();
                            detail.Number = row.Cells["Number"].FormattedValue.ToDecimal();
                            detail.GoodsName = row.Cells["GoodsName"].FormattedValue.ToString();
                            detail.WarehouseCode = row.Cells["WarehouseName"].Value.ToString();
                            detail.WarehouseName = row.Cells["WarehouseName"].FormattedValue.ToString();
                            detail.GoodsCode = row.Cells["GoodsCode"].FormattedValue.ToString();
                            detail.GoodsSpec = row.Cells["GoodsSpec"].FormattedValue.ToString();
                            detail.GoodsUnit = row.Cells["GoodsUnit"].FormattedValue.ToString();
                            detail.SaleReturnDetailCode = row.Cells["SaleReturnDetailCode"].FormattedValue.ToString();
                            detail.SaleReturnCode = row.Cells["SaleReturnCodeD"].FormattedValue.ToString();
                            detail.SaleReturnInWarehouseCode = row.Cells["SaleReturnInWarehouseCodeD"].FormattedValue.ToString();
                            detail.SaleReturnInWarehouseDetailCode = row.Cells["SaleReturnInWarehouseDetailCode"].FormattedValue.ToString();
                            detail.Remark = row.Cells["RemarkD"].FormattedValue.ToString();
                            dataDetails.Add(detail);
                        }
                    }
                    if (_w_SaleReturnInWarehouseServices.UpdateSaleReturnInWarehouseInfo(model, dataDetails))
                    {
                        MessageBox.Show("保存成功！", "提示");
                        SetDataToDetail(GetDetailData(model.SaleReturnInWarehouseCode));
                    }
                }
                SetToolButtonStatus(formStatus);
                //列表重新赋值
                this.dataGridViewList.DataSource = GetData();
            }
        }

        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnDel.Enabled = !isAdd;
            SetDataToDetail(GetDetailData(SaleReturnInWarehouseCode.Text));
        }

        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                if (_w_SaleReturnInWarehouseServices.DeleteSaleReturnInWarehouseInfo(new w_SaleReturnInWarehouse()
                {
                    ID = txtID.Text.ToInt32(),
                    SaleReturnInWarehouseCode = SaleReturnInWarehouseCode.Text
                }))
                {
                    formStatus = FormStatus.Del;
                    SetToolButtonStatus(formStatus);
                    //列表重新赋值
                    dataGridViewDetail.Rows.Clear();
                    this.dataGridViewList.DataSource = GetData();
                }
            }
        }

        public override void SetToolButtonStatus(FormStatus status)
        {
            base.SetToolButtonStatus(status);
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        dataGridViewDetail.ReadOnly = false;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        dataGridViewDetail.ReadOnly = true;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }

        public override bool ValidateData()
        {
            return true;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private List<w_SaleReturnInWarehouse> GetData()
        {
            List<w_SaleReturnInWarehouse> data = new List<w_SaleReturnInWarehouse>();
            data = _w_SaleReturnInWarehouseServices.Query();
            return data;
        }
        /// <summary>
        /// 明细表 设置数据 --销售退货单号带出
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_SaleReturnDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["SaleReturnCodeD"].Value = p.SaleReturnCode;
                row.Cells["SaleReturnDetailCode"].Value = p.SaleReturnDetailCode;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["GoodsName"].Value = p.GoodsName;
                row.Cells["WarehouseName"].Value = "CK001";
                row.Cells["WarehouseCode"].Value = "CK001";
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["Number"].Value = p.Number;
                row.Cells["RemarkD"].Value = p.Remark;

            });
        }
        /// <summary>
        /// 明细表 设置数据 --主表带出
        /// </summary>
        /// <param name="details"></param>
        private void SetDataToDetail(List<w_SaleReturnInWarehouseDetail> details)
        {
            dataGridViewDetail.Rows.Clear();
            details.ForEach(p =>
            {
                dataGridViewDetail.Rows.AddCopy(dataGridViewDetail.Rows.Count - 1);
                DataGridViewRow row = dataGridViewDetail.Rows[dataGridViewDetail.Rows.Count - 2];
                row.Cells["SaleReturnCodeD"].Value = p.SaleReturnCode;
                row.Cells["SaleReturnDetailCode"].Value = p.SaleReturnDetailCode;
                row.Cells["SaleReturnInWarehouseCodeD"].Value = p.SaleReturnInWarehouseCode;
                row.Cells["SaleReturnInWarehouseDetailCode"].Value = p.SaleReturnInWarehouseDetailCode;
                row.Cells["WarehouseName"].Value = p.WarehouseCode;
                row.Cells["WarehouseCode"].Value = p.WarehouseCode;
                row.Cells["GoodsCode"].Value = p.GoodsCode;
                row.Cells["GoodsName"].Value = p.GoodsName;
                row.Cells["GoodsSpec"].Value = p.GoodsSpec;
                row.Cells["GoodsUnit"].Value = p.GoodsUnit;
                row.Cells["Number"].Value = p.Number;
                row.Cells["RemarkD"].Value = p.Remark;
            });
        }
        /// <summary>
        /// 获取明细数据
        /// </summary>
        /// <returns></returns>
        private List<w_SaleReturnInWarehouseDetail> GetDetailData(string code)
        {
            List<w_SaleReturnInWarehouseDetail> data = new List<w_SaleReturnInWarehouseDetail>();
            data = _wSaleReturnInWarehouseDetailServices.QueryListByClause(p => p.SaleReturnInWarehouseCode == code);
            return data;
        }

        private void SaleReturnCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(SaleReturnCode.Text.Trim()))
                {
                    var data = _wSaleReturnServices.QueryByClause(p => p.SaleReturnCode.Equals(SaleReturnCode.Text.Trim()));
                    if (data != null)
                    {
                        CustomerName.Text = data.CustomerName;
                        CustomerCode.Text = data.CustomerCode;

                        List<w_SaleReturnDetail> details = new List<w_SaleReturnDetail>();
                        details = _wSaleReturnDetailServices.QueryListByClause(p => p.SaleReturnCode == data.SaleReturnCode);
                        SetDataToDetail(details);
                    }
                    else
                    {
                        //GoodsName.DataSource=new List<w_SaleReturnDetail>();;
                        MessageBox.Show("销售退货单号不存在！");
                    }
                }
            }
        }

        private void SetDataGridViewReadonlyStatus()
        {
            dataGridViewDetail.ReadOnly = false;
            string[] cols = { "Number", "WarehouseName", "RemarkD" };
            foreach (DataGridViewColumn column in dataGridViewDetail.Columns)
            {
                if (!cols.Contains(column.Name))
                {
                    column.ReadOnly = true;
                }
            }
        }
    }
}
